package com.lmuse.xmr.foodspotting.ui.homepage;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dexafree.materialList.card.Card;
import com.dexafree.materialList.card.CardProvider;
import com.dexafree.materialList.listeners.OnDismissCallback;
import com.dexafree.materialList.listeners.RecyclerItemClickListener;
import com.dexafree.materialList.view.MaterialListView;
import com.donkingliang.banner.CustomBanner;
import com.lmuse.xmr.foodspotting.R;
import com.lmuse.xmr.foodspotting.db.ArticlePresenterImpl;
import com.lmuse.xmr.foodspotting.db.CollectPresenterImpl;
import com.lmuse.xmr.foodspotting.db.Contract;
import com.lmuse.xmr.foodspotting.db.RecipePresenterImpl;
import com.lmuse.xmr.foodspotting.db.UserPresenterImpl;
import com.lmuse.xmr.foodspotting.model.Recipe;
import com.lmuse.xmr.foodspotting.model.User;
import com.lmuse.xmr.foodspotting.model._Article;
import com.lmuse.xmr.foodspotting.ui.recipe.RecipeActivity;
import com.lmuse.xmr.foodspotting.ui.search.SearchActivity;
import com.lmuse.xmr.foodspotting.util.Statistics;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;

public class HomepageFragment extends Fragment implements Contract.RecipeView, Contract.ArticleView,
        Contract.CollectView, Contract.UserView{

    private CustomBanner<String> recommendBanner;
    private MaterialListView cardList;
    private EditText searchEt;

    private Contract.RecipePresenter recipePresenter;
    private Contract.ArticlePresenter articlePresenter;
    private Contract.CollectPresenter collectPresenter;
    private Contract.UserPresenter userPresenter;

    private ArrayList<String> recommendUrlList;
    private List<_Article> articleList;
    private int limit = 6; //每页个数 || 查询条数
    private List<Recipe> recipeList;
    private String favorite; //用户喜爱的标签

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_homepage, container, false);
        recipePresenter = new RecipePresenterImpl(this);
        articlePresenter = new ArticlePresenterImpl(this);
        collectPresenter = new CollectPresenterImpl(this);
        userPresenter = new UserPresenterImpl(this);
        initView(view);

        return view;
    }

    private void initView(View view) {
        searchEt = (EditText) view.findViewById(R.id.et_search);
        searchEt.setOnFocusChangeListener(new FocusChangeListener());
        recommendUrlList = new ArrayList<>();
        recommendBanner = (CustomBanner) view.findViewById(R.id.banner_recommend);
        recommendBanner.setOnPageClickListener(new BannerClickListener());
        cardList = (MaterialListView) view.findViewById(R.id.cardlist_homepage);
        cardList.addOnItemTouchListener(new CardClickListener());
        cardList.setOnDismissCallback(new CardDismissCallBack());

        recipeList = new ArrayList<>();
        recommendUrlList = new ArrayList<>();

        articlePresenter.queryArticle();

        userPresenter.getUserInfoCache();
    }

    //设置普通指示器
    private void setBean(final ArrayList beans) {
        recommendBanner.setPages(new CustomBanner.ViewCreator<String>() {
            @Override
            public View createView(Context context, int position) {
                ImageView imageView = new ImageView(context);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                return imageView;
            }

            @Override
            public void updateUI(Context context, View view, int position, String entity) {
                Glide.with(context).load(entity).into((ImageView) view);
            }
        }, beans).startTurning(3000);  //设置自动翻页
    }

    class FocusChangeListener implements View.OnFocusChangeListener {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (b) { // 获得焦点
                searchEt.clearFocus();
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            } else { // 失去焦点

            }
        }
    }

    class BannerClickListener implements CustomBanner.OnPageClickListener {
        @Override
        public void onPageClick(int i, Object o) {
            Intent startIntent = new Intent(getActivity(),
                    ArticleActivity.class);
            startIntent.putExtra("item", i + "");
            startActivity(startIntent);
//            Toast.makeText(getActivity(), "点击了第" + i + "项", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(getActivity(), ArticleActivity.class);
//            intent.putExtra("article", articleList.get(i).getUrl());
//            startActivity(intent);
        }
    }

    class CardClickListener implements RecyclerItemClickListener.OnItemClickListener {

        @Override
        public void onItemClick(@NonNull Card card, int position) {
            Intent startIntent = new Intent(getActivity(),
                    RecipeActivity.class);
            startIntent.putExtra(com.lmuse.xmr.foodspotting.constants.Recipe.ID,
                    recipeList.get(position).getObjectId());
            startActivity(startIntent);
        }

        @Override
        public void onItemLongClick(@NonNull Card card, int position) {

        }
    }

    class CardDismissCallBack implements OnDismissCallback {
        @Override
        public void onDismiss(@NonNull Card card, int position) {
            /*int count = (page + 1) * limit - 2;
            if (position == count) {
                Toast.makeText(getActivity(), "当前第" + count + "个", Toast.LENGTH_SHORT).show();
                page++;
                recipePresenter.queryRecipe("label", labelTitle.getText().toString(), limit, page);
            }*/
        }
    }

    @Override
    public void onQueryArticleSuccess(List<_Article> articleList) {

        this.articleList = articleList;

        ArrayList<String> recommendUrlList = new ArrayList<>();
        for (_Article article : articleList) {
            recommendUrlList.add(article.getCover());
        }
        this.recommendUrlList = recommendUrlList;
        setBean(recommendUrlList);
    }

    @Override
    public void onQueryArticleFailed(String msg) {

    }

    @Override
    public void onSignUpSuccess(User user) {

    }

    @Override
    public void onSignUpFailed(String msg) {

    }

    @Override
    public void onSignInSuccess(User user) {

    }

    @Override
    public void onSignInFailed(String msg) {

    }

    @Override
    public void onUserInfoCache(User user) {
        if (user != null) {
            collectPresenter.queryCollecting();
        }else {
            //先判断用户有没有喜爱的标签，没有再默认推荐西点类别
            recipePresenter.queryRecipe("label", "西点", limit);
        }
    }

    @Override
    public void onUpdateUserSuccess() {

    }

    @Override
    public void onUpdateUserFailed(String msg) {

    }

    @Override
    public void onRequestEmailVerifyResult(BmobException e) {

    }

    @Override
    public void onResetPasswordByEmailResult(BmobException e) {

    }

    @Override
    public void onQueryUserByIdSuccess(User user) {

    }

    @Override
    public void onQueryUserByIdFailed(String msg) {

    }

    @Override
    public void onQueryUserAmountSuccess(int size) {

    }

    @Override
    public void onQueryUserAmountFailed(String msg) {

    }

    @Override
    public void onQueryByKeySuccess(List<User> userList) {

    }

    @Override
    public void onQueryByKeyFailed(String msg) {

    }

    @Override
    public void onUploadingImg(Integer value) {

    }

    @Override
    public void onUploadingImg(int curIndex, int curPercent, int total, int totalPercent) {

    }

    @Override
    public void onUploadImgSuccess(BmobFile cover) {

    }

    @Override
    public void onUploadImgSuccess(List<String> urls) {

    }

    @Override
    public void onUploadImgFailed(String msg) {

    }

    @Override
    public void onAddRecipeSuccess() {

    }

    @Override
    public void onAddRecipeFailed(String msg) {

    }

    @Override
    public void onQueryRecipeSuccess(Recipe recipe) {

    }

    @Override
    public void onQueryRecipeSuccess(List<Recipe> recipeList) {
        this.recipeList = recipeList;
        //        Toast.makeText(getActivity(), "请求完成", Toast.LENGTH_SHORT).show();
        cardList.getAdapter().clearAll();
        for (Recipe recipe : recipeList) {
            Card card = new Card.Builder(getActivity())
                    .setTag("BIG_IMAGE_CARD")
                    .withProvider(new CardProvider())
                    .setLayout(R.layout.material_big_image_card_layout)
                    .setTitle(recipe.getTitle())
                    .setTitleColor(getResources().getColor(R.color.colorWhite))
                    .setDrawable(recipe.getCoverUrl())
                    .endConfig()
                    .build();
            cardList.getAdapter().add(card);
        }
        cardList.smoothScrollToPosition(0);
    }

    @Override
    public void onQueryRecipeFailed(String msg) {
        Toast.makeText(getActivity(), "请求数据失败!(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCollectRecipeSuccess() {

    }

    @Override
    public void onCollectRecipeFailed(String msg) {

    }

    @Override
    public void onCancelCollectSuccess() {

    }

    @Override
    public void onCancelCollectFailed(String msg) {

    }

    @Override
    public void onQueryCollectingSuccess(List<Recipe> recipeList) {
        if (recipeList.size() != 0) {
            List<String> labelList = new ArrayList<>();
            for (Recipe recipe : recipeList) {
                labelList.add(recipe.getLabel());
            }

            //查找用户收藏最多标签的食谱列表
            recipePresenter.queryRecipe("label", Statistics.AppearenceMax(labelList), 5);
        }else {

            //先判断用户有没有喜爱的标签，没有再默认推荐西点类别
            recipePresenter.queryRecipe("label", "西点", limit);
        }

    }

    @Override
    public void onQueryCollectingFailed(String msg) {
        Toast.makeText(getActivity(), "请求数据失败!(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onQueryKeySuccess(List<Recipe> recipeKeyList) {

    }

    @Override
    public void onQueryKeyFailed(String msg) {

    }

    @Override
    public void onDeleteRecipeSuccess() {

    }

    @Override
    public void onDeleteRecipeFailed(String msg) {

    }
}